package socket;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {
    private ServerSocket serverSocket;
    private ExecutorService pool;

    public Server() {
        try {
            System.out.println("正在启动服务端");
            serverSocket = new ServerSocket(8088);
            pool = Executors.newFixedThreadPool(5);
            System.out.println("服务端启动成功");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void start() {
        try {
            while ( true){
                System.out.println("等待客户端连接...");
                Socket socket = serverSocket.accept();// 监听
                System.out.println("一个客户端连接了");
                ClientHandler handler = new ClientHandler(socket);
//                Thread t = new Thread(handler);
//                t .start();
                pool.execute(handler);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    public static void main(String[] args) {
        Server server = new Server();
        server.start();
    }

    private class ClientHandler implements Runnable{
        private Socket socket;
        public ClientHandler(Socket socket){
            this.socket = socket;
        }

        @Override
        public void run() {
            try {

                InputStream in = socket.getInputStream();
                int d;
                while ((d = in.read())!=-1){
                    byte[] bytes = new byte[d];
                    in.read(bytes);
                    String line = new String(bytes, StandardCharsets.UTF_8);
                    System.out.println("客户说："+line);
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
}

}
